// 获取教师列表数据
function fetchTeacherList(pageNum = 1, pageSize = 10) {
  fetch('http://localhost:8083/api/admin/teacher/list', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      pageNum: pageNum,
      pageSize: pageSize
    }),
  })
    .then(response => response.json())
    .then(data => {
      if (data.code === 200) {
        teacherData = data.data.records;  // 假设返回数据中有 records 字段
        updateTeacherList();
      } else {
        alert('获取教师数据失败');
      }
    })
    .catch(error => {
      console.error('Error fetching teacher list:', error);
    });
}

// 新增教师
function addTeacher(teacher) {
  fetch('http://localhost:8083/api/admin/teacher/add', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(teacher),
  })
    .then(response => response.json())
    .then(data => {
      if (data.code === 200) {
        alert('教师添加成功');
        fetchTeacherList();  // 刷新教师列表
      } else {
        alert('教师添加失败');
      }
    })
    .catch(error => {
      console.error('Error adding teacher:', error);
    });
}

// 编辑教师
function updateTeacher(teacher) {
  fetch('http://localhost:8083/api/admin/teacher/update', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(teacher),
  })
    .then(response => response.json())
    .then(data => {
      if (data.code === 200) {
        alert('教师更新成功');
        fetchTeacherList();  // 刷新教师列表
      } else {
        alert('教师更新失败');
      }
    })
    .catch(error => {
      console.error('Error updating teacher:', error);
    });
}

// 删除教师
function deleteTeacher(id) {
  fetch(`http://localhost:8083/api/admin/teacher/delete/${id}`, {
    method: 'POST',
  })
    .then(response => response.json())
    .then(data => {
      if (data.code === 200) {
        alert('教师删除成功');
        fetchTeacherList();  // 刷新教师列表
      } else {
        alert('教师删除失败');
      }
    })
    .catch(error => {
      console.error('Error deleting teacher:', error);
    });
}

// 更新教师状态（激活/未激活）
function updateStatus(id, status) {
  fetch(`http://localhost:8083/api/admin/teacher/status/${id}?status=${status}`, {
    method: 'POST',
  })
    .then(response => response.json())
    .then(data => {
      if (data.code === 200) {
        alert('状态更新成功');
        fetchTeacherList();  // 刷新教师列表
      } else {
        alert('状态更新失败');
      }
    })
    .catch(error => {
      console.error('Error updating status:', error);
    });
}

// 打开模态框（新增或编辑）
function openModal(mode, teacher = {}) {
  const modal = document.getElementById('teacher-modal');
  const form = document.getElementById('teacher-form');
  const title = document.getElementById('modal-title');

  if (mode === 'create') {
    title.textContent = '新增教师';
    form.reset();
    document.getElementById('teacher-id').value = '';
  } else if (mode === 'edit') {
    title.textContent = '编辑教师';
    document.getElementById('teacher-id').value = teacher.id;
    document.getElementById('teacher-name').value = teacher.name;
    document.getElementById('teacher-realname').value = teacher.realname;
    document.getElementById('teacher-contact').value = teacher.contact;
    document.getElementById('teacher-email').value = teacher.email;
    document.getElementById('teacher-status').value = teacher.status;
  }

  modal.style.display = "block";
}

// 关闭模态框
function closeModal() {
  document.getElementById('teacher-modal').style.display = "none";
}

// 提交表单（新增或更新教师）
function submitForm(event) {
  event.preventDefault(); // 阻止默认的表单提交行为

  const id = document.getElementById('teacher-id').value || null;
  const name = document.getElementById('teacher-name').value;
  const realname = document.getElementById('teacher-realname').value;
  const contact = document.getElementById('teacher-contact').value;
  const email = document.getElementById('teacher-email').value;
  const status = document.getElementById('teacher-status').value;

  const teacher = { id, name, realname, contact, email, status };

  if (id) {
    // 编辑模式
    updateTeacher(teacher);  // 调用API更新教师
  } else {
    // 新增模式
    addTeacher(teacher);  // 调用API新增教师
  }

  closeModal();
}

// 更新教师列表
function updateTeacherList() {
  const tableBody = document.getElementById('teacher-table-body');
  tableBody.innerHTML = '';  // 清空表格内容

  teacherData.forEach(teacher => {
    const row = document.createElement('tr');
    row.innerHTML = `
      <td>${teacher.id}</td>
      <td>${teacher.name}</td>
      <td>${teacher.realname}</td>
      <td>${teacher.contact}</td>
      <td>${teacher.email}</td>
      <td>${teacher.status === 'active' ? '激活' : '未激活'}</td>
      <td>
        <button onclick="updateStatus(${teacher.id}, '${teacher.status === 'active' ? 'inactive' : 'active'}')">${teacher.status === 'active' ? '激活' : '未激活'}</button>
        <button onclick="openModal('edit', ${JSON.stringify(teacher)})">编辑</button>
        <button onclick="deleteTeacher(${teacher.id})">删除</button>
      </td>
    `;
    tableBody.appendChild(row);
  });
}

// 页面加载时获取教师列表
document.addEventListener("DOMContentLoaded", function() {
  fetchTeacherList();  // 从后台获取教师列表
});

// 搜索教师
function searchTeacher() {
  const searchTerm = document.getElementById('search-teacher').value.toLowerCase();
  const filteredTeachers = teacherData.filter(teacher =>
    teacher.name.toLowerCase().includes(searchTerm) ||
    teacher.realname.toLowerCase().includes(searchTerm)
  );
  renderTeacherList(filteredTeachers);
}

// 渲染教师列表（搜索后的展示）
function renderTeacherList(teachers) {
  const tableBody = document.getElementById('teacher-table-body');
  tableBody.innerHTML = '';

  teachers.forEach(teacher => {
    const row = document.createElement('tr');
    row.innerHTML = `
      <td>${teacher.id}</td>
      <td>${teacher.name}</td>
      <td>${teacher.realname}</td>
      <td>${teacher.contact}</td>
      <td>${teacher.email}</td>
      <td>${teacher.status === 'active' ? '激活' : '未激活'}</td>
      <td>
        <button onclick="updateStatus(${teacher.id}, '${teacher.status === 'active' ? 'inactive' : 'active'}')">${teacher.status === 'active' ? '激活' : '未激活'}</button>
        <button onclick="openModal('edit', ${JSON.stringify(teacher)})">编辑</button>
        <button onclick="deleteTeacher(${teacher.id})">删除</button>
      </td>
    `;
    tableBody.appendChild(row);
  });
}

// 点击退出按钮时的跳转操作
document.querySelector(".logout-btn").addEventListener("click", function() {
  window.location.href = "../login.html"; // 跳转到登录页面
});
